<template>
  <div v-if="currentCommentId" class="comment-bubble-menu">
    <ToolbarButton
      :icon="
        isResolved ? 'i-ri-checkbox-circle-fill' : 'i-ri-checkbox-circle-line'
      "
      :title="isResolved ? '取消解决' : '解决'"
      hide-text
      @click="resolveComment"
    />
    <ToolbarButton
      v-if="!isResolved && currentCommentId"
      icon="i-ri-delete-bin-line"
      title="删除"
      hide-text
      class="comment-button-danger"
      @click="handleDeleteClick"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, inject, ref, watch, type Ref } from "vue";
import type { Editor } from "@tiptap/vue-3";
import { ElMessageBox } from "element-plus";
import ToolbarButton from "../button/index.vue";
import { commentActions } from "../../store/comment";

const editor = inject<Ref<Editor>>("editor");

const currentCommentId = ref<string | null>(null);

// 监听编辑器选择变化，获取当前选中的批注ID
watch(
  () => {
    if (!editor?.value?.state) return null;
    return editor.value.state.selection;
  },
  (selection) => {
    if (!editor?.value || !editor.value.state || !selection) {
      currentCommentId.value = null;
      return;
    }

    try {
      const { from, to } = selection;
      if (from === to) {
        currentCommentId.value = null;
        return;
      }

      // 查找选中文本中的批注标记
      // 方法1: 通过遍历节点查找
      let foundCommentId: string | null = null;
      editor.value.state.doc.nodesBetween(from, to, (node, pos) => {
        if (node.isText) {
          // 获取该文本节点在文档中的位置
          const nodeFrom = pos;

          // 检查该节点位置的所有marks
          const marksAtPos = editor.value.state.doc.resolve(nodeFrom).marks();
          marksAtPos.forEach((mark) => {
            if (mark.type.name === "comment" && mark.attrs.commentId) {
              foundCommentId = mark.attrs.commentId;
            }
          });

          // 也检查节点本身的marks
          node.marks.forEach((mark) => {
            if (mark.type.name === "comment" && mark.attrs.commentId) {
              foundCommentId = mark.attrs.commentId;
            }
          });
        }
        if (foundCommentId) return false; // 找到后停止遍历
      });

      // 方法2: 如果方法1没找到，尝试通过editor.isActive检查
      if (!foundCommentId && editor.value.isActive("comment")) {
        // 尝试从选区的marks中获取
        const marks = editor.value.state.selection.$from.marks();
        marks.forEach((mark) => {
          if (mark.type.name === "comment" && mark.attrs.commentId) {
            foundCommentId = mark.attrs.commentId;
          }
        });
      }

      currentCommentId.value = foundCommentId;
    } catch (error) {
      console.warn("获取批注ID失败:", error);
      currentCommentId.value = null;
    }
  },
  { immediate: true, deep: true }
);

// 判断当前批注是否已解决
const isResolved = computed(() => {
  if (!currentCommentId.value) return false;
  const comment = commentActions.getComment(currentCommentId.value);
  return comment?.isResolved || false;
});

// 解决/取消解决批注
const resolveComment = () => {
  if (!currentCommentId.value || !editor?.value) return;
  const currentUserId = "current-user-id"; // TODO: 获取当前用户ID
  commentActions.toggleResolve(
    currentCommentId.value,
    currentUserId,
    editor.value
  );
};

// 处理删除按钮点击
const handleDeleteClick = async () => {
  if (!currentCommentId.value || !editor?.value) return;

  try {
    await ElMessageBox.confirm("确定要删除这条批注吗？", "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 用户确认删除
    deleteComment();
  } catch (error) {
    // 用户取消删除，不做任何操作
  }
};

// 删除批注
const deleteComment = () => {
  if (!currentCommentId.value) {
    console.warn("删除批注失败: currentCommentId 为空");
    return;
  }
  if (!editor?.value) {
    console.warn("删除批注失败: editor 为空");
    return;
  }

  const commentIdToDelete = currentCommentId.value;

  try {
    commentActions.deleteComment(commentIdToDelete, editor.value);
    currentCommentId.value = null;
  } catch (error) {
    console.error("删除批注时出错:", error);
  }
};
</script>

<style lang="scss" scoped>
.comment-bubble-menu {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px;
  background: var(--editor-color-white);
  border: 1px solid var(--editor-border-color);
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.comment-button-danger {
  :deep(.toolbar-button) {
    color: var(--el-color-danger);

    &:hover {
      background: rgba(var(--el-color-danger-rgb), 0.1);
    }
  }
}
</style>
